# -*- coding: utf-8 -*-

import cgi, re, os

import urllib2
from google.appengine.api import urlfetch

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from google.appengine.ext.webapp import template

from google.appengine.ext import db

import Cookie
import ConfigParser

def error(msg, errTitle):
		error_msg = {
				'errTitle': errTitle, 
				'error': msg,
				}
		path = os.path.join(os.path.dirname(__file__), 'templates/error.html')
		return template.render(path, error_msg) 

def lang(self):
	cookie = Cookie.SimpleCookie(self.request.headers.get('Cookie'))
	if cookie.has_key('lang'):
		lang = cookie['lang'].value
		if lang == 'ru_RU':
			LangDirPath = 'lang/ru'
		elif lang == 'de_DE':
			LangDirPath = 'lang/de'
		else:
			LangDirPath = 'lang/en'
	else:
		LangDirPath = 'lang/en'
	return LangDirPath   

def LangMass (LangFilePath):
	LangFileOpen = open(LangFilePath).readlines()
	LangMass = []
	for line in LangFileOpen:
		try:
			LangMass.append(re.match(r"(?P<var>\w*) *= *(?P<val>.*)", line).groupdict())
		except:
			pass
	
	template_values = {}
	for i in range(len(LangMass)):
		template_values[LangMass[i]['var']] = LangMass[i]['val']
	return template_values

class MainPage(webapp.RequestHandler):
		def get(self):
				# MAIN
				LangFile = 'main.txt'
				LangDirPath = lang(self)
				LangFilePath = os.path.join(LangDirPath, LangFile)
				template_values = LangMass(LangFilePath)

				path = os.path.join(os.path.dirname(__file__), 'templates/main.html')
				self.response.out.write(template.render(path, template_values))

class Links(webapp.RequestHandler):
		def post(self):
				usercoords = cgi.escape(self.request.get('content'))
				testusercoords = re.match('.*?\d\d?\.?\d+?, *?\d\d?\.?\d+.*?', usercoords)

				# If test OK
				if testusercoords:
						#Google Maps Link generating
						gmapslink = 'http://maps.google.com/maps?f=q&source=s_q&hl=en&q='
						usercoordsclean = usercoords.replace(' ', '%20')
						userlink = gmapslink + usercoordsclean
						
						#Shorting Link
						apiurl = 'http://tinyurl.com/api-create.php?url='
						shortuserlink = urllib2.urlopen(apiurl + userlink).read()
						
						# Getting Lang dictionary
						LangFile = 'links.txt'
						LangDirPath = lang(self)
						LangFilePath = os.path.join(LangDirPath, LangFile)
						template_values = LangMass(LangFilePath)
						
						template_values.update ({
								'userlink': userlink,
								'usercoords': usercoords,
								'shortuserlink': shortuserlink,
						})
						
						# OK
						path = os.path.join(os.path.dirname(__file__), 'templates/links.html')
						self.response.out.write(template.render(path, template_values))
						
				else:
						# Error: bad coordinates
						# Getting Lang dictionary
						LangFile = 'error.txt'
						LangDirPath = lang(self)
						LangFilePath = os.path.join(LangDirPath, LangFile)
						template_values = LangMass(LangFilePath)
						self.response.out.write(error(template_values['sBad_coords'], template_values['sSometh_wrong']))

class Address(webapp.RequestHandler):
		def post(self):
				useraddress = cgi.escape(self.request.get('enterd_address'))
				if useraddress:
						usercity = cgi.escape(self.request.get('enterd_city'))
						usercountry = cgi.escape(self.request.get('enterd_country'))
						address = useraddress + usercity + usercountry
						address = address.replace(' ', '%20')

						geokey = 'ABQIAAAAZSF8yBDYqCOEagFKE44naRRy1uusy0BXeZnc8fFavcbwKyanyhRO0RU_tI8PEgz-60reBTsh9inDIg'
						addressreq = 'http://maps.google.ru/maps/geo?q=%s&output=csv&key=%s&oe=utf8' % (address, geokey)
						
						addressreq = addressreq.encode('utf8')
						coords = urllib2.urlopen(addressreq).read()
						
						latlong = re.match(r"(?P<code>\d*),\d*,(?P<lat>\d*(\.?\d*)?),(?P<lon>\d*(\.\d*)?)", coords).groupdict()

						latitude = latlong['lat']
						longitude = latlong['lon']
						geocodecode = latlong['code']
						
						if geocodecode == '620':
								# Error: 620
								# Getting Lang dictionary
								LangFile = 'error.txt'
								LangDirPath = lang(self)
								LangFilePath = os.path.join(LangDirPath, LangFile)
								template_values = LangMass(LangFilePath)
								self.response.out.write(error(template_values['sTo_Many'], template_values['sSometh_wrong']))
								
						elif latitude == '0' and longitude == '0':
								# Error: no place
								# Getting Lang dictionary
								LangFile = 'error.txt'
								LangDirPath = lang(self)
								LangFilePath = os.path.join(LangDirPath, LangFile)
								template_values = LangMass(LangFilePath)
								self.response.out.write(error(template_values['sNo_place'], template_values['sSometh_wrong']))
						else:
								# OK
								# Getting Lang dictionary
								LangFile = 'address.txt'
								LangDirPath = lang(self)
								LangFilePath = os.path.join(LangDirPath, LangFile)
								template_values = LangMass(LangFilePath)
				
								template_values.update ({
										'useraddress': useraddress,
										'latitude': latitude,
										'longitude': longitude,
								})
								
								path = os.path.join(os.path.dirname(__file__), 'templates/address.html')
								self.response.out.write(template.render(path, template_values))
				else:
						LangFile = 'error.txt'
						LangDirPath = lang(self)
						LangFilePath = os.path.join(LangDirPath, LangFile)
						template_values = LangMass(LangFilePath)
						self.response.out.write(error(template_values['sNo_street'], template_values['sSometh_wrong']))
						
class Naoborot(webapp.RequestHandler):
		def get(self):
				path = os.path.join(os.path.dirname(__file__), 'templates/naoborot.html')
				self.response.out.write(template.render(path, {}))
				
class NaoborotResult(webapp.RequestHandler):
		def post(self):
				usertext = cgi.escape(self.request.get('content'))
				resulttext = ''
				for i in range(len(usertext)):
					resulttext += usertext[(len(usertext)-1)-i]
				
				#path = os.path.join(os.path.dirname(__file__), 'templates/naoborot-result.html')
				#self.response.out.write(template.render(path, {'usertext': usertext, 'resulttext': resulttext}))
				self.response.out.write(resulttext)

class Shows(webapp.RequestHandler):
		def get(self):
			class Shows(db.Model):
				name = db.StringProperty()
				date = db.DateTimeProperty()
				id = db.IntegerProperty()
				showid = db.IntegerProperty()
			
			shows = []
			quer = db.GqlQuery("SELECT * FROM Shows ORDER BY date DESC")
			result = quer.fetch(5)
			for i in result:
				shows.append('<b>' + i.name + '</b><br /><i>' + str(i.date) + '</i>')
			
			#SHOWS
			showslist = 'The Big Bang Theory, Fringe, House M.D., Dexter'
			
			path = os.path.join(os.path.dirname(__file__), 'templates/shows.html')
			self.response.out.write(template.render(path, {'shows': shows, 'showslist':showslist}))

class Showsupd(webapp.RequestHandler):
	def get(self):
		import datetime
		
		class Shows(db.Model):
			name = db.StringProperty()
			date = db.DateTimeProperty()
			id = db.IntegerProperty()
			showid = db.IntegerProperty()
		
		import feedparser
		feed_url = "http://www.tvseries.me/feed/"
		feed = feedparser.parse(feed_url)

		# showid:
		# 1 - The Big Bang Theory
		# 2 - Fringe
		# 3 - House M.D.
		# 4 - Dexter
		
		potencshows = []
		for j in range(len(feed['entries'])):
			if re.findall(r'big bang theory', feed['entries'][j]['title'] , re.IGNORECASE):
				potencshows.append({'name':feed['entries'][j]['title'], 'id':int(str(feed['entries'][j]['id'])[-4:]), 'showid':1, 'time':datetime.datetime(feed['entries'][j]['updated_parsed'].tm_year, feed['entries'][j]['updated_parsed'].tm_mon, feed['entries'][j]['updated_parsed'].tm_mday, feed['entries'][j]['updated_parsed'].tm_hour, feed['entries'][j]['updated_parsed'].tm_min)})
			elif re.findall(r'fringe', feed['entries'][j]['title'] , re.IGNORECASE):
				potencshows.append({'name':feed['entries'][j]['title'], 'id':int(str(feed['entries'][j]['id'])[-4:]), 'showid':2, 'time':datetime.datetime(feed['entries'][j]['updated_parsed'].tm_year, feed['entries'][j]['updated_parsed'].tm_mon, feed['entries'][j]['updated_parsed'].tm_mday, feed['entries'][j]['updated_parsed'].tm_hour, feed['entries'][j]['updated_parsed'].tm_min)})
			elif re.findall(r'house m.d.', feed['entries'][j]['title'] , re.IGNORECASE):
				potencshows.append({'name':feed['entries'][j]['title'], 'id':int(str(feed['entries'][j]['id'])[-4:]), 'showid':3, 'time':datetime.datetime(feed['entries'][j]['updated_parsed'].tm_year, feed['entries'][j]['updated_parsed'].tm_mon, feed['entries'][j]['updated_parsed'].tm_mday, feed['entries'][j]['updated_parsed'].tm_hour, feed['entries'][j]['updated_parsed'].tm_min)})
			elif re.findall(r'dexter', feed['entries'][j]['title'] , re.IGNORECASE):
				potencshows.append({'name':feed['entries'][j]['title'], 'id':int(str(feed['entries'][j]['id'])[-4:]), 'showid':4, 'time':datetime.datetime(feed['entries'][j]['updated_parsed'].tm_year, feed['entries'][j]['updated_parsed'].tm_mon, feed['entries'][j]['updated_parsed'].tm_mday, feed['entries'][j]['updated_parsed'].tm_hour, feed['entries'][j]['updated_parsed'].tm_min)})
			else:
				pass
		
		import time
		if potencshows:
			for i in range(len(potencshows)):
				q = db.GqlQuery("SELECT * FROM Shows WHERE id=%s" % int(potencshows[i]['id']))
				result = q.fetch(1)
				if result:
					pass
				else:
					show = Shows(
						name = potencshows[i]['name'],
						date = potencshows[i]['time'],
						id = potencshows[i]['id'],
						showid = potencshows[i]['showid']
						)
					show.put()
				


application = webapp.WSGIApplication([
			('/', MainPage),
			('/links', Links),
			('/address', Address),
			('/naoborot', Naoborot),
			('/naoborot-result', NaoborotResult),
			('/shows', Shows),
			('/showsupd/', Showsupd)], 
			debug=True)

def main():
		run_wsgi_app(application)

if __name__ == "__main__":
		main()
		